//
//  HXSendNotifyViewController.m
//  KD
//
//  Created by Hubery on 16/2/2.
//  Copyright © 2016年 ifly. All rights reserved.
//

#import "HXSendNotifyViewController.h"
#import "HXSendNotifyHeadView.h"
#import "HXSelectedPersonViewController.h"
#import "HXSelectedAreaMapViewController.h"
#import "HXSelecteManageViewController.h"

@interface HXSendNotifyViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,HXSelectedPersonViewControllerDelegate,HXSelectedAreaMapViewControllerDelegate,HXSelecteManageViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,assign) NSInteger tableViewRow;
@property(nonatomic,strong) NSMutableArray *questionArray;
@property(nonatomic,weak) HXSendNotifyHeadView *headerView;
@property(nonatomic,assign) NSInteger imageBtnTag;
@property(nonatomic,strong) NSMutableDictionary *dataDict;
@property(nonatomic,strong)  NSMutableArray<NSDictionary *> *userIdListArray;
@property (weak, nonatomic) IBOutlet UIView *selectedPersonView;
@end

@implementation HXSendNotifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self.sendType isEqualToString:@"zhuguan"]) {
        self.title = @"发送内部通知";
    }else{
        self.title = @"发送会议通知";
    }
    [self setUpBarBtn];
//    [self setUpFootView];
    self.tableView.tableFooterView = [[UIView alloc]init];
    HXSendNotifyHeadView *sendHeader = [[[NSBundle mainBundle]loadNibNamed:@"HXSendNotifyHeadView" owner:self options:nil]lastObject];
    self.tableView.tableHeaderView = sendHeader;
    self.headerView = sendHeader;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    self.selectedPersonView.userInteractionEnabled = YES;
    [self.selectedPersonView addGestureRecognizer:tap];
    [tap addTarget:self action:@selector(selectedPerson)];
}

-(void)selectedPerson{
    if ([self.sendType isEqualToString:@"qiye"]) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"HXInform" bundle:nil];
        HXSelectedPersonViewController *vc = [sb instantiateViewControllerWithIdentifier:@"HXSelectedPersonViewController"];
        vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([self.sendType isEqualToString:@"zhuguan"]){
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"HXInform" bundle:nil];
        HXSelecteManageViewController *vc = [sb instantiateViewControllerWithIdentifier:@"HXSelecteManageViewController"];
       vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (IBAction)selectedMeetiogLocationBtnClick:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"HXInform" bundle:nil];
    HXSelectedAreaMapViewController *vc = [sb instantiateViewControllerWithIdentifier:@"HXSelectedAreaMapViewController"];
    vc.mapEnumType = MapTypeMeetingType;
    vc.delegate = self;
    vc.isSelectd = NO;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -HXSelectedAreaMapViewControllerDelegatre
-(void)location:(NSMutableDictionary *)locationDict{
    self.headerView.userLocationDict = locationDict;
}

-(void)setUpBarBtn{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    button.size = CGSizeMake(70, 30);
    button.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [button setTitle:@"发布" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(send) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
}

-(void)send{
    NSString *str = [NSString string];
    NSMutableDictionary *mDict = [self.headerView getMessage:&str];
    if (mDict == nil) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",str]];
        return;
    }
    self.dataDict = mDict;
    if (![[UserDefaultHandler getUserDetault:kID] boolValue]) {
        [SVProgressHUD showErrorWithStatus:@"请登录"];
        return;
    }
    if (self.userIdListArray.count==0) {
        [SVProgressHUD showErrorWithStatus:@"请选择人员"];
        return;
    }
    NSString *openStr = [NSString stringWithFormat:@"%@:00",[self.dataDict objectForKey:@"Mess_OpenDate"]];
    NSString *endStr = [NSString stringWithFormat:@"%@:00",[self.dataDict objectForKey:@"Mess_EndDate"]];
    if (!([GlobalUtil compareDate:endStr withDate:openStr] == -1)) {
        [SVProgressHUD showErrorWithStatus:@"截止时间必须大于开会时间"];
        return;
    }
//    NSMutableArray *questArray = [[NSMutableArray alloc]init];
//    for (NSString *str in self.questionArray) {
//        NSMutableDictionary *questDict = [[NSMutableDictionary alloc]init];
//        [questDict setObject:str forKey:@"Que_Content"];
//        [questDict setObject:[self.dataDict objectForKey:@"Mess_EndDate"] forKey:@"Que_EndDate"];
//        [questArray addObject:questDict];
//    }
//    [self.dataDict setObject:questArray forKey:@"questList"];
    [self.dataDict setObject:self.userIdListArray forKey:@"useridlist"];
    [self.dataDict setObject:[UserDefaultHandler getUserDetault:kID] forKey:@"Mess_UserID"];
    [SVProgressHUD showWithStatus:@"正在发送" ];
    if([self.sendType isEqualToString:@"qiye"]){
        [self.dataDict setObject:@"1" forKey:@"Mess_Type"];
        [NetworkAPI sendNotifyWithDict:self.dataDict
                               success:^(HXBaseModel *result) {
                                   [SVProgressHUD dismiss];
                                   if ([result.code isEqualToString:@"200"]) {
                                       [SVProgressHUD showSuccessWithStatus:@"发送成功"];
                                       [self.superVc actionRefreshData];
                                       [self.navigationController popViewControllerAnimated:YES];
                                   }else{
                                       [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                   }
                                   
                               }failure:^(NSError *err) {
                                   [SVProgressHUD showErrorWithStatus:@"网络错误"];
                               }];
    }else if([self.sendType isEqualToString:@"zhuguan"]){
        [NetworkAPI sendManageNotifyWithDict:self.dataDict
    success:^(HXBaseModel *result) {
        [SVProgressHUD dismiss];
        if ([result.code isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:@"发送成功"];
            [self.superVc actionRefreshData];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }
        
    }failure:^(NSError *err) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
    }
}

- (IBAction)addimageBtnCilck:(UIButton *)sender {
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
    }
    pickerImage.delegate = self;
    pickerImage.allowsEditing = YES;
    [self presentViewController:pickerImage animated:YES completion:^{
        self.imageBtnTag = 1;
    }];
}

- (IBAction)addimageTwoBtnCilck:(UIButton *)sender {
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
    }
    pickerImage.delegate = self;
    pickerImage.allowsEditing = YES;
    [self presentViewController:pickerImage animated:YES completion:^{
        self.imageBtnTag = 2;
    }];
}

#pragma mark - HXSelectedPersonViewControllerDelegate 选企业人员归来
- (void)getPersonMsg:(NSArray *)idArray nameArray:(NSArray *)nameArray{
    if (idArray.count == 0)return;
    for (NSString *str in idArray) {
        NSDictionary *dict = [NSDictionary dictionaryWithObject:str forKey:@"MU_UserID"];
        [self.userIdListArray addObject:dict];
    }
    self.headerView.nameArray = nameArray;
}

#pragma mark - HXSelecteManageViewControllerDelegate 选主管归来
-(void)getManagePersonMsg:(NSArray *)idArray nameArray:(NSArray *)nameArray{
    if (idArray.count == 0)return;
    for (NSString *str in idArray) {
        NSDictionary *dict = [NSDictionary dictionaryWithObject:str forKey:@"MU_UserID"];
        [self.userIdListArray addObject:dict];
    }
    self.headerView.nameArray = nameArray;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
        UIImage *originalImage =  (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
        if(!originalImage){
            originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
        }
    [self setUpIconBtnWithImage:originalImage];
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

-(void)setUpIconBtnWithImage:(UIImage*)image{
    [self.headerView setImage:image tag:self.imageBtnTag];
}
//
//#pragma mark - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}
//
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    HXQuestionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HXQuestionTableViewCell" forIndexPath:indexPath];
//    if (self.questionArray.count>indexPath.row) {
//        cell.questionMessage = self.questionArray[indexPath.row];
//    }else{
//        cell.questionMessage = nil;
//    }
//    cell.delegate = self;
//    cell.row = (int)indexPath.row;
//    return cell;
//}
//
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//}
//
//-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
//    if(editingStyle == UITableViewCellEditingStyleDelete)
//    {
//        self.tableViewRow--;
//        [self.tableView reloadData];
//        if (self.questionArray.count!=0) {
//            [self.questionArray removeObjectAtIndex:indexPath.row];
//        }
//        
////        HXLog(@"%@",self.questionArray);
////        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];//动画删除指定的行
//    }
//}
//

#pragma mark - HXQuestionTableViewCellDelegate
//-(void)questionMessage:(NSString *)str row:(NSInteger)row{
//    if (self.questionArray.count==row) {
//        [self.questionArray addObject:str];
////        HXLog(@"%@",self.questionArray);
//    }else if (self.questionArray.count>row){
//        [self.questionArray replaceObjectAtIndex:row withObject:str];
////        HXLog(@"%@",self.questionArray);
//    }else{
//        //NSAssert(0, @"编辑问题时出错");
//    }
//}

//-(NSString*)tableView:(UITableView*)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath*)indexpath {
//    return @" 删除";
//}

//- (NSMutableArray *)questionArray{
//    if (_questionArray == nil) {
//        _questionArray = [[NSMutableArray alloc]initWithCapacity:0];
//    }
//    return _questionArray;
//}

//-(void)setUpFootView{
//    UIView *view = [[UIView alloc]init];
//    view.height = 26;
//    self.tableView.tableFooterView = view;
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [view addSubview:btn];
//    btn.frame = CGRectMake(17, 4, 70, 22);
//    [btn addTarget:self action:@selector(addCell) forControlEvents:UIControlEventTouchUpInside];
//    btn.layer.cornerRadius=9.0f;
//    [btn setTitle:@"添加问题" forState:UIControlStateNormal];
//    btn.titleLabel.font = [UIFont boldSystemFontOfSize:12];
//    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [btn setBackgroundColor:MAINCOLOR];
//}

//-(void)addCell{
//    if (self.tableViewRow == 2) {
//        [SVProgressHUD showErrorWithStatus:@"只能添加两个问题"];
//        return;
//    }
//    if (self.tableViewRow == self.questionArray.count) {
//        self.tableViewRow++;
//        [self.tableView reloadData];
//    }else if (self.tableViewRow > self.questionArray.count){
//        [SVProgressHUD showErrorWithStatus:@"请逐个添加问题"];
//    }else{
//        //NSAssert(0, @"添加问题时出错");
//    }
//}

- (NSMutableDictionary *)dataDict{
    if (!_dataDict) {
        _dataDict = [[NSMutableDictionary alloc]init];
    }
    return _dataDict;
}

-(NSMutableArray<NSDictionary *> *)userIdListArray{
    if (!_userIdListArray) {
        _userIdListArray = [[NSMutableArray alloc]init];
    }
    return _userIdListArray;
}


@end
